package com.example.java8;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class TreeTest {
    public static void main(String[] args) {
        TreeTest treeTest = new TreeTest();
        ArrayList<Node> nodes = new ArrayList<>();
//        Node n0 = new Node("01", "0");
//        nodes.add(n0);
//        Node n1 = new Node("0101", "01");
//        nodes.add(n1);
//        Node n2 = new Node("010101", "0101");
//        nodes.add(n2);
//        Node n3 = new Node("010102", "0101");
//        nodes.add(n3);
//        Node n4 = new Node("0102", "01");
//        nodes.add(n4);
//        Node n5 = new Node("010201", "0102");
//        nodes.add(n5);
//        Node n6 = new Node("01010101", "010101");
//        nodes.add(n6);
//        Node n7 = new Node("02", "0");
//        nodes.add(n7);
//        Node n8 = new Node("0201", "02");
//        nodes.add(n8);
//        Node n9 = new Node("020101", "0201");
//        nodes.add(n9);

        Node n0 = new Node("01");
        nodes.add(n0);
        Node n1 = new Node("0101" );
        nodes.add(n1);
        Node n2 = new Node("010101");
        nodes.add(n2);
        List<Node> nodeList = treeTest.buildTree(nodes);
        System.out.println();

    }
    public List<Node> buildTree(List<Node> nodeList){
        //按父级节点进行分组
        Map<String, List<Node>> parentNodeMap = nodeList.stream().collect(Collectors.groupingBy(Node::getpId));


        //所有字典项map
        Map<String, Node> allNodeMap = nodeList.stream()
                .collect(Collectors.toMap(Node::getId, node -> node));

        List<Node> returnList = new ArrayList<>();

        nodeList.forEach(node -> {
            if (!allNodeMap.containsKey(node.getpId())) {
                //父节点，递归添加子节点
                addChildren(parentNodeMap, node);
                returnList.add(node);
            }
        });

        return returnList;
    }

    private void addChildren(Map<String, List<Node>> parentNodeMap, Node node) {
        if(parentNodeMap.containsKey(node.getId())){
            List<Node> childList = parentNodeMap.get(node.getId());
            node.setChildren(childList);
            childList.forEach(childDict->{
                addChildren(parentNodeMap, childDict);
            });
        }
    }


}

class Node {
    public Node(String id, String pId) {
        this.id = id;
        this.pId = pId;
    }

    public Node(String id) {
        this.id = id;
    }

    private String id;
    private String pId;

    private List<Node> children;

    public List<Node> getChildren() {
        return children;
    }

    public void setChildren(List<Node> children) {
        this.children = children;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getpId() {
        return pId;
    }

    public void setpId(String pId) {
        this.pId = pId;
    }
}